<template>
	<view  class="coreshop-bg-white">
		<u-toast ref="uToast" /><u-no-network></u-no-network>
		<u-navbar title="添加商品" safeAreaInsetTop fixed placeholder>
		    <view class="coreshop-navbar-left-slot" slot="left">
		        <u-icon name="arrow-left" size="19" @click="goNavigateBack"></u-icon>
		        <u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
		        <u-icon name="home" size="22" @click="goHome"></u-icon>
		    </view>
		    <view slot="right">
		    </view>
		</u-navbar>
		
		<view class="coreshop-padding-10">
			<u--form :model="form" :rules="rules" ref="uForm" errorType="message" labelPosition="left" labelWidth="80">
			    <u-form-item label="商品名称" prop="name" borderBottom clearValidate>
			        <u--input v-model="form.name" placeholder="请填写商品名称" />
			    </u-form-item>
			    <u-form-item label="商品价格" prop="price" borderBottom clearValidate>
			        <u--input type="digit" v-model="form.price" placeholder="请填写商品价格" />
			    </u-form-item>
				<u-form-item label="商品图片640*640" borderBottom>  
						<!-- <image class='coreshop-avatar xl radius bg-gray' mode="aspectFill" :src="form.images" @click="uploadLogo"></image> -->
						 <u-upload :fileList="good1"
						            @afterRead="addGoodImg"
						            @delete="deleteGoodImg"
						            name="1"
						 		    multiple
									width="80"
									height="80"
						            :maxSize="2 * 1024 * 1024" 
						            :maxCount="1"></u-upload> 
				</u-form-item>
				<u-form-item label="商品分类" borderBottom clearValidate>
				    <u--input v-model="form.goodsCategoryName" placeholder="请填写商品分类" />
				</u-form-item>
				<u-form-item label="品牌" borderBottom clearValidate>
					<u--input v-model="form.brandName" placeholder="请选择品牌" @focus="show = true"/>
					<u-picker :show="show" :columns="brandList" keyName="label" @cancel="show = false" @confirm="onConfirm" :closeOnClickOverlay="true" @close="show = false"></u-picker> 
				</u-form-item>
				<u-form-item label="备注" borderBottom clearValidate>
				    <u--textarea v-model="form.remark" placeholder="请填写备注"></u--textarea>
				</u-form-item>
			</u--form>	
		</view>
		<view class="coreshop-bg-white coreshop-footer-fixed coreshop-foot-padding-bottom"> 
			 <u-button type="success" text="保存" @click="saveOperation" :disabled='submitStatus' :loading='submitStatus'></u-button>
		</view>
	</view>
</template>

<script>
	export default{
		data() {
		    return {
				upLoadAction: this.$globalConstVars.apiBaseUrl + '/Api/Common/UploadImages',
				good1:[],
		        form: {
		            name: '',
		            price: '' ,
					images:'/static/images/common/add.jpeg', 
					goodsCategoryName:'',
					brandId: null,
					brandName:'',
					remark:''
		        },
				dealerId:'',
				submitStatus: false,
				brandList: [],
				show: false,
				rules: {
				    name: [
				        {
				            required: true,
				            message: '请输入商品名称',
				            trigger: 'blur',
				        }
				    ],
					price: [
					    {
							type:"float",
					        required: true,
					        message: '请填写商品价格',
					        trigger: 'blur',
					    }
					] 
				}	
		    }
		}, 
		onShow() {
			this.getAllBrands();
		},
		//加载执行
		onLoad: function (options) {
		    let store = options.store;
			let model=JSON.parse(store);
		    this.dealerId = model.dealerId; 
		   if(model.id!==undefined){
				this.form.name=model.name;
				this.form.id=model.id;
				this.form.price=model.price;
				// this.form.images=model.image;
				if(model.image) this.good1.push({url:model.image});
				this.form.goodsCategoryName=model.goodsCategoryName;
				this.form.brandId=model.brandId;
				this.form.brandName=model.brandName;
				this.form.remark=model.remark;
		   }
		},
		methods:{
			//保存
			saveOperation() {
			    this.$refs.uForm.validate().then(res => {
					 this.submitStatus = false;
					 if (!this.form.name) {
					     this.$u.toast('请输入商品名称')
					     return false
					 } else if (!this.form.price || isNaN(this.form.price)) {
					     this.$u.toast('请输入商品价格')
					     return false
					 // }else if (!this.form.images || this.form.images=='/static/images/common/add.jpeg') {
						}else   if (this.good1.length <= 0) {
					     this.$u.toast('请上传商品图片')
					     return false
					 } else if (!this.form.brandName) {
					     this.$u.toast('请选择品牌')
					     return false
					 } 
					 
					 this.form.images=this.good1[0].url;
					 this.form.dealerId=this.dealerId;
					   
					 if(this.form.id==null){
						 this.form.bn=this.getSN("BN");
						 this.form.sn=this.getSN("SN");
						 this.doAddGoodsByDealer();
					 }else{
						  this.doEditGoodsByDealer();
					 }
				});
			},
			doAddGoodsByDealer(){
				this.$u.api.doAddGoodsByDealer(this.form).then(res => {
					  this.submitStatus = false;
				      if (res.status) {
				          this.$refs.uToast.show({
				              message: res.msg, type: 'success', complete: function () {
				                  uni.navigateBack({
				                      delta: 1
				                  });
				              }
				          })
				      } else {
				          this.$u.toast(res.msg);
				      }
				});
			},
			doEditGoodsByDealer(){
				this.$u.api.doEditGoodsByDealer(this.form).then(res => {
					  this.submitStatus = false;
				      if (res.status) {
				          this.$refs.uToast.show({
				              message: res.msg, type: 'success', complete: function () {
				                  uni.navigateBack({
				                      delta: 1
				                  });
				              }
				          })
				      } else {
				          this.$u.toast(res.msg);
				      }
				});
			},
			//获取品牌信息
			getAllBrands(){
				let self=this;
				this.$u.api.getAllBrands().then(res => {
				    if (res.status) {
						if (res.data) {
							self.brandList=[];
							let brandList=[]
						    for (let i = 0; i < res.data.length; i++) { 
								brandList.push({
									id:res.data[i].id,
									label:res.data[i].name
								});
						    }
							 self.brandList.push(brandList) 
						}
					}
				})
			},
			onConfirm(e) { 
					this.form.brandId=e.value[0].id;
					this.form.brandName=e.value[0].label;
					this.show=false;
			} ,
			// 上传图片
			/* uploadLogo() {
			    this.$upload.uploadFiles(null, res => {
			        if (res.status) {
			            this.form.images = res.data.src;
			        } else {
			            this.$u.toast(res.msg)
			        }
			    })
			}, */
			async addGoodImg(event){
							// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
							let lists = [].concat(event.file)
							let fileListLen = this[`good${event.name}`].length
							lists.map((item) => {
							    this[`good${event.name}`].push({
							        ...item,
							        status: 'uploading',
							        message: '上传中'
							    })
							})
							for (let i = 0; i < lists.length; i++) {
							    const result = await this.uploadFilePromise(lists[i].thumb)
							    var jmResult = JSON.parse(result);
							    console.log(result);
							    let item = this[`good${event.name}`][fileListLen]
							    this[`good${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							        status: 'success',
							        message: '',
							        url: jmResult.data.src
							    }))
							    fileListLen++
							}
						}, 
			//删除图片
			deleteGoodImg(event){
				this[`good${event.name}`].splice(event.index, 1)
			},
			uploadFilePromise(url) {
			    return new Promise((resolve, reject) => {
			        let a = uni.uploadFile({
			            url: this.upLoadAction, // 仅为示例，非真实的接口地址
			            fileType: 'image',
			            filePath: url,
			            header: {
			                'Accept': 'application/json',
			                'Content-Type': 'multipart/form-data',
			                'Authorization': 'Bearer ' + this.$db.get('userToken')
			            },
			            name: 'file',
			            success: (res) => {
			                setTimeout(() => {
			                    resolve(res.data)
			                }, 1000)
			            }
			        });
			    })
			},
			 //获取随机编码
			getSN(str) {
			     //声明一个随机数变量，默认为1
			     var GetRandomn = 1;
			     //js生成时间戳
			     var timestamp = new Date().getTime();
			     //获取随机范围内数值的函数
			     function GetRandom(n) {
			         //由随机数+时间戳+1组成
			         GetRandomn = Math.floor(Math.random() * n + timestamp + 1);
			     }
			     //开始调用，获得一个1-100的随机数
			     GetRandom("30");
			     return str + GetRandomn;
			}
		}
	}
</script>

<style>
</style>